<?php
/**
 * Bootstrap
 */

defined("DEBUG_MODE") or define("DEBUG_MODE", FALSE);

if(DEBUG_MODE){
	$start = microtime(true);
	error_reporting(E_ALL);
}else{
	error_reporting(0);
}

if (ini_get('register_globals')) {
	$allowed = array('_ENV' => 1, '_GET' => 1, '_POST' => 1, '_COOKIE' => 1, '_FILES' => 1, '_SERVER' => 1, '_REQUEST' => 1, 'GLOBALS' => 1);
	foreach ($GLOBALS as $key => $value) {
		if (!isset($allowed[$key])) {
			unset($GLOBALS[$key]);
		}
	}
}


function pithy_valid_http_host($host){
	return preg_match('/^\[?(?:[a-z0-9-:\]_]+\.?)+$/', $host);
}

function conf_init(){
	global $base_url, $base_path, $base_root;
	global $conf;

	$conf = array();

	if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
		$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
	}

	if(isset($_SERVER['HTTP_HOST'])){
		$_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);

		if (!pithy_valid_http_host($_SERVER['HTTP_HOST'])) {
			// HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
			header($_SERVER['SERVER_PROTOCOL'] .' 400 Bad Request');
			exit;
		}
	}else{
		$_SERVER['HTTP_HOST'] = '';
	}

	if(file_exists(BASEPATH . 'cfg/setting.php')){
		$conf = include_once BASEPATH . 'cfg/setting.php';
	}

	if(isset($conf['base_url'])){
		$base_url = $conf['base_url'];
		$parts = parse_url($base_url);

		if(!isset($parts['path'])){
			$parts['path'] = '';
		}

		$base_path = $parts['path'] . '/';
		$base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
	}else{
		$base_root = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';

		$base_url = $base_root .= '://' . $_SERVER['HTTP_HOST'];

		if($dir = trim(dirname($_SERVER['SCRIPT_NAME']), '\,/')){
			$base_path = "/$dir";
			$base_url .= $base_path;
			$base_path .= '/';
		}else{
			$base_path = '/';
		}
	}

	/*
	 * Cookie  AND  Session Path
	 */
	if(isset($conf['cookie_domain'])){
		$cookie_domain = $conf['cookie_domain'];
		$session_name = $cookie_domain;
	}else{
		list( , $seesion_name) = explode('://', $base_url, 2);

		if(!empty($_SERVER['HTTP_HOST'])){
			$cookie_domain = $_SERVER['HTTP_HOST'];
			// Strip leading periods, www., and port numbers from cookie domain.
			$cookie_domain = ltrim($cookie_domain, '.');
			if (strpos($cookie_domain, 'www.') === 0) {
				$cookie_domain = substr($cookie_domain, 4);
			}
			$cookie_domain = explode(':', $cookie_domain);
			$cookie_domain = '.'. $cookie_domain[0];
			$conf['cookie_domain'] = $cookie_domain;
		}
	}

	// To prevent session cookies from being hijacked, a user can configure the
	// SSL version of their website to only transfer session cookies via SSL by
	// using PHP's session.cookie_secure setting. The browser will then use two
	// separate session cookies for the HTTPS and HTTP versions of the site. So we
	// must use different session identifiers for HTTPS and HTTP to prevent a
	// cookie collision.
	if (ini_get('session.cookie_secure')) {
		$session_name .= 'SSL';
	}

	if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
		ini_set('session.cookie_domain', $cookie_domain);
	}
	
	session_name('SESS' . md5($seesion_name));
}

function variable_init($conf = array()){
	
	$db = load_database();
	
	$vars = array();
	
	$result = $db->query("SELECT * FROM {variable}");
	
	while($r = $db->fetchArray($result)){
		$vars[$r['name']] = unserialize($r['value']);	
	}
	
	foreach($conf as $name => $value){
		$vars[$name] = $value;
	}
	
	return $vars;
}

function variable_get($name, $default) {
  global $conf;

  return isset($conf[$name]) ? $conf[$name] : $default;
}

function variable_set($name, $value) {
  global $conf;

  $db = load_database();
  $serialized_value = serialize($value);
  $db->query("UPDATE {variable} SET value = '%s' WHERE name = '%s'", $serialized_value, $name);
  if (!$db->affectedRows()) {
    @$db->query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, $serialized_value);
  }

  $conf[$name] = $value;
}

function variable_del($name){
	global $conf;
	
	$db = load_database();
	$db->query("DELETE FROM {variable} WHERE name = '%s'", $name);
	
	unset($conf[$name]);
}

function pithy_is_front_page(){
	static $is_front_page;
	
	if(!isset($is_front_page)){
		$is_front_page = ($_GET['q'] == variable_get('default_controller', 'home/index'));
	}
	
	return $is_front_page;
}

/**
 * 
 * 执行日志记录~~~
 * 
 * @param unknown_type $msg
 * @param unknown_type $type
 */
function traclog($msg = NULL, $type = 'runtime'){
	//=Do Nothing
}


//=System Run;

function _bootstrap(){
	global $conf;
	
	//=Step 1 初始化配置信息
	conf_init();
	
	//=Step 2 Page Cache 
	
	
	//=Step 3 Database 
	require_once BASEPATH . 'lib/db/DB.php';
	require_once BASEPATH . 'lib/common/common.php';
	
	//=Step 3 Lock Or Deny
	
	
	//=Step 4 Session Init
	
	
	//=Step 5 Variable Init
	$conf = variable_init($conf);
	
	
	//=Step 6 Bootstrap Full
	require_once BASEPATH . 'lib/core/Pithy.php';
	require_once BASEPATH . 'lib/core/Router.php';
	require_once BASEPATH . 'lib/core/Action.php';
	require_once BASEPATH . 'lib/core/WebSession.php';
	require_once BASEPATH . 'lib/core/View.php';
	
	//header("Content-Type: text/html;charset=" . variable_get('default_charset', 'utf-8') . '"');
	header("Content-Type: text/html; charset=utf-8");
	//=Run
	new Pithy();
}

//Pithy Run;
_bootstrap();

if(DEBUG_MODE){
	$end = microtime(true);

	echo '<div style="border-top:1px solid #d4d4d4;background:#f1f1f7;position:absolute;left:0;bottom:0;width:100%;padding:1em 0;text-indent:2em;">'
	. number_format(($end - $start) * 1000, 2) . ' 毫秒 </div>';
}